import { ref } from 'vue'
import { defineStore } from 'pinia'
import API from '@/http'

export const useCreditCardStore = defineStore('credit-card', () => {
  const creditCardList = ref([])
  const defaultCard = ref({})

  async function getCreditCardList() {
    try {
      const response = await API.Payment.getPaymentMethods({ data: {} })
      creditCardList.value = response
      defaultCard.value = creditCardList.value.find((card) => card.is_default) || creditCardList.value[0]
    } catch (e) {
      console.error(e)
    }
  }

  async function onSelectCard(card) {
    if (card.is_ban) return

    defaultCard.value = card
    try {
      console.log(`預設信用卡: ${card.id}`)
      await API.Payment.bindDefaultPayment({ data: { payment_method_id: card.id } })
      await getCreditCardList()
    } catch (e) {
      console.error(e)
    }
  }

  return { creditCardList, defaultCard, getCreditCardList, onSelectCard }
})
